/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.spring.tracing;

import javax.servlet.http.HttpServletRequest;

import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.web.servlet.HandlerMapping;

/**
 * Resolves transaction name using {@link HttpServletRequest#getMethod()} and templated route that
 * handled the request. To return correct transaction name, it must be used after request is
 * processed by {@link org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping}
 * where {@link HandlerMapping#BEST_MATCHING_PATTERN_ATTRIBUTE} is set.
 */
@ApiStatus.Internal
public final class TransactionNameProvider {
    /**
     * provide transaction name
     *
     * @param request for get attribute BEST_MATCHING_PATTERN_ATTRIBUTE
     * @return transaction name
     */
    public @Nullable String provideTransactionName(final @NotNull HttpServletRequest request) {
        final String pattern =
            (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);

        if (pattern != null) {
            return request.getMethod() + " " + pattern;
        } else {
            return null;
        }
    }
}
